package com.nstskj.study.netty.tcp.netty.protocol.handler.msg;

import com.nstskj.study.netty.tcp.netty.protocol.message.in.msg.base.AbstractInputNetTcpMessage;
import com.nstskj.study.netty.tcp.netty.protocol.message.out.msg.base.AbstractOutputNetTcpMessage;
import com.nstskj.study.netty.tcp.netty.protocol.session.base.AbstractSession;
import com.nstskj.study.netty.tcp.util.TcpSessionUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;

/**
 * @author ZhouChuGang
 * @version 1.0
 * @project nstskj-study-netty-tcp-spring
 * @date 2021/5/4 8:39
 * @Description 抽象协议处理者
 */
@Slf4j
public abstract class AbstractProtocolHandler<I extends AbstractInputNetTcpMessage, O extends AbstractOutputNetTcpMessage> implements ProtocolHandler {

    /**
     * 真正的协议处理 ，之类需要自己实现
     *
     * @param abstractInputNetTcpMessage
     * @param session
     * @return
     */
    public abstract O doHandlerCmdMsg(I abstractInputNetTcpMessage, AbstractSession session);

    /**
     * 执行命令处理
     *
     * @param abstractInputNetTcpMessage
     * @return
     */
    @Override
    public AbstractOutputNetTcpMessage handlerCmdMsg(AbstractInputNetTcpMessage abstractInputNetTcpMessage) {
        //得到设备会话
        AbstractSession session = TcpSessionUtils.getSessionByTcpMessage(abstractInputNetTcpMessage);
        AbstractOutputNetTcpMessage outputNetTcpMessage = doHandlerCmdMsg((I) abstractInputNetTcpMessage, session);
        if (Objects.nonNull(outputNetTcpMessage)) {
            //拷贝通用属性
            outputNetTcpMessage.setHead(abstractInputNetTcpMessage.getHead());
            outputNetTcpMessage.setVersion(abstractInputNetTcpMessage.getVersion());
            outputNetTcpMessage.setCmd(abstractInputNetTcpMessage.getCmd());
            outputNetTcpMessage.setSerial(abstractInputNetTcpMessage.getSerial());
            outputNetTcpMessage.setAttributeMap(abstractInputNetTcpMessage.getAttributeMap());
        }
        return outputNetTcpMessage;
    }
}
